package net.libra.animatedBitmap
{
	import flash.display.Shape;
	import flash.events.Event;
	import flash.utils.getTimer;

	/**
	 * 
	 * @author elvisjiang
	 * 
	 */
	public class JTick
	{
		
		/**
		 * 单例模式
		 */
		private static var instance:JTick;
		
		/**
		 * 事件的载体。可以是主类Main，也可以是一个shape。
		 * 只要是EventDispatcher的子类即可。
		 */
		private var shape:Shape;
		
		/**
		 * 需要注册EnterFrame事件的JBitmap的集合
		 */
		private var bitmapAry:Vector.<IJTickable>;
		
		/**
		 * 最大两帧间隔（防止待机后返回卡死） 
		 */
		static public const MAX_INTERVAL:int = 3000;
		static public const MIN_INTERVAL:int = 0;
		
		/**
		 * 速度系数
		 * 可由此实现慢速播放
		 */		
		public var speed:Number = 1.0;
		
		private var prevTime:int;//上次记录的时间
		
		/**
		 * 构造函数，
		 * @param	shape，事件的载体。EventDispatcher的子类
		 */
		public function JTick(shape:Shape) { 
			this.shape = shape;
			bitmapAry = new Vector.<IJTickable>();
			instance = this;
			this.shape.addEventListener(Event.ENTER_FRAME, onEnterFrameHandler);
		}
		
		/**
		 * 增加一个需要注册EnterFrame事件的JBitmap
		 * @param	r JBitmap
		 */
		public function addItem(item:IJTickable):void {
			for each(var r:IJTickable in bitmapAry)
			{
				if(r._name == item._name)
				{
					return;
				}
			}
			this.bitmapAry[this.bitmapAry.length] = item;
		}
		/**
		 * 返回item 
		 */ 
		public function getItemByName(name:String):IJTickable
		{
			for each(var r:IJTickable in bitmapAry)
			{
				if(r._name == name)
				{
					return r;
				}
			}
			return null;
		}
		public function removeItem(item:IJTickable):void {
			bitmapAry.splice(bitmapAry.indexOf(item),1);
		}
		
		/**
		 * EnterFrame事件循环。
		 * @param	e
		 */
		private function onEnterFrameHandler(e:Event):void {
			var nextTime:int = getTimer();
			var interval:int;
			if (prevTime == 0) interval = 0;
			else {
				interval = max(MIN_INTERVAL, min(nextTime - prevTime, MAX_INTERVAL));
				for each(var r:IJTickable in bitmapAry) {
					r.tick(interval * speed);
				}
			}
			prevTime = nextTime;
		}
		
		private function max(a:int,b:int):int{
			return a > b ? a : b;
		}
		
		private function min(a:int,b:int):int{
			return a > b ? b : a;
		}
		
		/**
		 * 获取当前实例。
		 * @return
		 */
		public static function getInstance():JTick {
			return instance ||= new JTick(new Shape());
		}
		
	}
}